package me.jiatao.mybatisstudy.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.ArrayList;
import java.util.List;


@EnableTransactionManagement
@Configuration
//使用通用Mapper配置
@tk.mybatis.spring.annotation.MapperScan("me.jiatao.mybatisstudy.mapper.tk")

//mybatis 与 mybatis plus
@org.mybatis.spring.annotation.MapperScan("me.jiatao.mybatisstudy.mapper.plus")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 拦截全表的 更新 和 删除 操作
     * 当包含where 限定时，则不起作用
     * 线上环境需要关闭
     *
     * @return
     */
    @Bean
    public PaginationInterceptor sqlExplainInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();

        List<ISqlParser> sqlParserList = new ArrayList<>();
        // 攻击 SQL 阻断解析器、加入解析链
        sqlParserList.add(new BlockAttackSqlParser());
        paginationInterceptor.setSqlParserList(sqlParserList);

        return paginationInterceptor;
    }

    /**
     * SQL执行效率插件
     * 超过指定时间 自动取消执行
     */
    @Bean
    @Profile({"dev", "test"})// 设置 dev test 环境开启
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(100);//设置最大执行时间，单位毫秒
        performanceInterceptor.setFormat(true);//格式化SQL语句
        return performanceInterceptor;
    }


    /**
     * 乐观锁插件，自动把version加一
     *
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}
